package com.nice.rm.core;

import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 
 * 以追加的方式写文件
 * 
 * @author coder_czp-2015年4月30日
 */
public class LogAppendWriter implements Closeable {

    private long line;
    private File logPath;
    private BufferedWriter writer;

    public LogAppendWriter(File logPath) {
        this.logPath = logPath;
    }

    public synchronized void appendWrite(String lineStr) {
        try {
            if (writer == null) {
                if (!logPath.getParentFile().exists())
                    logPath.getParentFile().mkdirs();
                writer = new BufferedWriter(new FileWriter(logPath));
            }
            writer.write(lineStr);
            writer.write('\n');
            line++;
        } catch (IOException e) {
            close();
            throw new RuntimeException(e);
        }
    }

    public File getFile() {
        return this.logPath;
    }

    public synchronized void close() {
        if (writer != null)
            try {
                writer.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
    }

    public long getLine() {
        return line;
    }

}
